<template>
  <div class="page-wapper">
    <!-- 已发送日报管理 -->
    <div class="container">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">发送时间：</div>
            <!-- :default-time="['00:00:00', '23:59:59']" -->
            <el-date-picker
              v-model="filterData.reportTimeList"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              size="small"
            >
            </el-date-picker>
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
          @toggle-row-expand="toggleExpandChangeEvent"
        >
          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>

          <vxe-column type="expand" width="80" fixed="left">
            <template #content="{ row, rowIndex }">
              <div class="expand_wrapper">
                <div class="report_cell_title">
                  <span>上个工作日完成</span>
                  <span
                    v-if="row.lastFinishReportList.length"
                    class="time_text"
                  >
                    {{ row.lastFinishReportList[0].reportTime }}
                  </span>
                </div>

                <vxe-table
                  v-if="row.lastFinishReportList.length"
                  :data="row.lastFinishReportList"
                  :show-header="false"
                  :span-method="mergeRowMethod"
                  align="center"
                >
                  <vxe-column type="seq" title="序号" width="42"></vxe-column>

                  <vxe-column
                    title="模块名称"
                    field="moduleNames"
                    align="left"
                    header-align="center"
                  >
                    <template #default="{ row }">
                      <span v-for="(cell, j) in row.moduleNamesArr" :key="j">
                        【{{ cell }}】
                      </span>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportText"
                    title="工作内容"
                    min-width="300"
                    align="left"
                    header-align="center"
                  ></vxe-column>

                  <vxe-column title="工作进度" width="100">
                    <template #default="{ row }">
                      <div v-if="Number(row.workProgress)">
                        {{ row.workProgress }} %
                      </div>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportName"
                    title="报告人"
                    width="100"
                  ></vxe-column>
                </vxe-table>

                <!-- <div
                  v-if="row.lastFinishReportList.length"
                  class="report_cell_content"
                >
                  <div
                    v-for="(item, i) in row.lastFinishReportList"
                    :key="i"
                    class="report_cell_item"
                  >
                    <span class="nowrap">{{ i + 1 }}、</span>
                    <div class="f_1">
                      <span v-for="(cell, j) in item.moduleNamesArr" :key="j">
                        【{{ cell }}】
                      </span>
                      <span>{{ item.reportText }}</span>
                    </div>
                    <span v-if="Number(item.workProgress)" class="nowrap ml_s">
                      {{ item.workProgress }}%
                    </span>
                  </div>
                </div> -->
                <div v-else class="empty_box">无</div>

                <div class="report_cell_title">
                  <span>今日工作计划</span>
                  <span v-if="row.todayPlanReportList.length" class="time_text">
                    {{ row.todayPlanReportList[0].reportTime }}
                  </span>
                </div>

                <vxe-table
                  :data="row.todayPlanReportList"
                  :show-header="false"
                  :span-method="mergeRowMethod"
                  align="center"
                >
                  <vxe-column type="seq" title="序号" width="42"></vxe-column>

                  <vxe-column
                    title="模块名称"
                    field="moduleNames"
                    align="left"
                    header-align="center"
                  >
                    <template #default="{ row }">
                      <span v-for="(cell, j) in row.moduleNamesArr" :key="j">
                        【{{ cell }}】
                      </span>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportText"
                    title="工作内容"
                    min-width="300"
                    align="left"
                    header-align="center"
                  ></vxe-column>

                  <vxe-column title="工作进度" width="100">
                    <template #default="{ row }">
                      <div v-if="Number(row.workProgress)">
                        {{ row.workProgress }} %
                      </div>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportName"
                    title="报告人"
                    width="100"
                  ></vxe-column>
                </vxe-table>

                <!-- <div class="report_cell_content">
                  <div
                    v-for="(item, i) in row.todayPlanReportList"
                    :key="i"
                    class="report_cell_item"
                  >
                    <span class="nowrap">{{ i + 1 }}、</span>
                    <div class="f_1">
                      <span v-for="(cell, j) in item.moduleNamesArr" :key="j">
                        【{{ cell }}】
                      </span>
                      <span>{{ item.reportText }}</span>
                    </div>
                    <span v-if="Number(item.workProgress)" class="nowrap ml_s">
                      {{ item.workProgress }}%
                    </span>
                  </div>
                </div> -->

                <div class="report_cell_title">上个工作日问题反馈</div>

                <div v-if="row.reportCommitRemark" class="input_remark_box">
                  <span>{{ row.reportCommitRemark }}</span>
                </div>
                <div v-else class="empty_box">无</div>
              </div>
            </template>
          </vxe-column>

          <vxe-column
            field="createdTime"
            title="发送时间"
            width="160"
          ></vxe-column>

          <vxe-column
            field="reportCommitRemark"
            title="备注"
            align="left"
            header-align="center"
          ></vxe-column>

          <!-- <TableColum :colums="tableColum">
            <template #moduleNames="{ props }">
              <span v-for="(cell, j) in props.row.moduleNamesArr" :key="j">
                【{{ cell }}】
              </span>
            </template>
            <template #workProgress="{ props }">
              <div>{{ props.row.workProgress }} %</div>
            </template>
          </TableColum> -->

          <vxe-column #default="{ row }" width="100" title="操作" fixed="right">
            <div>
              <el-button size="mini" type="text" @click.stop="copyData(row)">
                复制
              </el-button>
              <el-button
                v-if="currentDateTime === row.dateStr"
                size="mini"
                type="text"
                style="color: #f78989"
                @click.stop="deleteTableDataMethod(row)"
              >
                撤回
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  getCurrentInstance,
  onActivated,
  toRefs,
  computed,
} from "vue";
import TableColum from "../../components/TabelTemplate/TableColum.vue";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import { copyInClip } from "../../utils/common";

const initFilterData = () => {
  return {
    reportTimeList: [],
    startDateTime: null,
    endDateTime: null,
  };
};

export default {
  name: "SendedReportManage",
  components: { TableColum },
  setup() {
    const { proxy } = getCurrentInstance();
    const $moment = proxy.$moment;
    const $api = proxy.$api;
    const store = useStore();

    // 当前的日期时间
    const currentDateTime = computed(() =>
      $moment(store.state.currentDateObj).format("YYYY-MM-DD")
    );

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});
    const searchBtnLoading = ref(false);

    // 预加载数据
    const prepareData = reactive({
      taskStatusSelectList: [],
      releaseIdSelectList: [],
      taskPrioritySelectList: [],
    });

    const tableState = reactive({
      columnsAll: {
        visible: true,
        title: "全选",
      },
      // 标签筛选列
      columns: [],
      // 列表标签筛选需要禁用筛选的选项
      disabledCancleColumns: ["序号", "操作"],
      xTable: null,
      tableData: [],
      tableLoading: false,
      tableColum: {
        moduleNames: {
          title: "模块名称",
          props: {
            sortable: false,
            align: "left",
            "header-align": "center",
            width: 250,
          },
          slotContent: "moduleNames",
        },
        reportText: {
          title: "工作内容",
          props: { sortable: false, align: "left", "header-align": "center" },
        },
        workProgress: {
          title: "工作进度",
          props: { sortable: false, width: 100 },
          slotContent: "workProgress",
        },
        reportTime: {
          title: "报告时间",
          props: { sortable: false, width: 130 },
        },
      },
    });

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      const params = {
        ...pagenationData,
        condition: {
          startCreatedTime: null,
          endCreatedTime: null,
        },
      };
      if (condition.reportTimeList && condition.reportTimeList.length) {
        params.condition.startCreatedTime = condition.reportTimeList[0];
        params.condition.endCreatedTime = condition.reportTimeList[1];
      }
      $api.reportCommit
        .listPageSelf(params)
        .then((res) => {
          tableState.tableLoading = false;
          // tableState.tableData = res.data.list.map((item) => {
          //   return {
          //     ...item,
          //     checked: false,
          //     moduleNamesArr: item.moduleNames
          //       .split("|")
          //       .filter((item) => item),
          //     moduleIdsArr: item.moduleIds.split("|").filter((item) => item),
          //   };
          // });
          tableState.tableData = res.data.list.map((item) => {
            return {
              ...item,
              lastFinishReportList: item.lastFinishReportList.map((cell) => {
                return {
                  ...cell,
                  checked: false,
                  moduleNamesArr: cell.moduleNames
                    .split("|")
                    .filter((it) => it),
                  moduleIdsArr: cell.moduleIds.split("|").filter((it) => it),
                };
              }),
              todayPlanReportList: item.todayPlanReportList.map((cell) => {
                return {
                  ...cell,
                  checked: false,
                  moduleNamesArr: cell.moduleNames
                    .split("|")
                    .filter((it) => it),
                  moduleIdsArr: cell.moduleIds.split("|").filter((it) => it),
                };
              }),
              dateStr: $moment(item.createdTime).format("YYYY-MM-DD"),
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(`确定要撤回今天的日报吗？`, "提示", {
        type: "warning",
      })
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 删除全部
    const deleteAll = () => {
      if (!tableState.tableData.length) {
        return ElMessage.warning("没啥可删的");
      }
      const selectedList = tableState.tableData.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          deleteTableData(ids);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableState.tableLoading = true;
      $api.reportCommit
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 查询已启用的所有角色列表
    // const getPreparedData = () => {
    //   $api.role
    //     .getEnableList()
    //     .then((res) => {
    //       prepareData.enableRoleSelectList = res.data || [];
    //     })
    //     .catch((err) => {
    //       console.error("getEnableList error: ", err);
    //     })
    //     .finally(() => {});
    // };

    // 筛选列-全选按钮
    const tagCheckedChange = (item) => {
      if (item.title === "全选") {
        // 点击全选操作
        tableState.columns.forEach((cell) => {
          cell.visible = item.visible;
          if (
            !item.visible &&
            tableState.disabledCancleColumns.includes(cell.title)
          ) {
            cell.visible = !item.visible;
          }
        });
      }
      tableState.columnsAll.visible = tableState.columns.every(
        (item) => item.visible
      );
      // 刷新布局
      tableState.xTable.refreshColumn();
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableState.tableData[rowIndex].checked) {
        return {
          backgroundColor: "pink",
        };
      }
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    const toggleExpandChangeEvent = () => {
      console.log("展开行事件");
    };

    const getModuleDisplayName = (row) => {
      if (!row.moduleNames) {
        return "";
      }
      let nameStr = "";
      const nameArr = row.moduleNames.split("|").filter((cell) => cell);
      nameArr.forEach((item) => {
        nameStr += `【${item}】`;
      });
      return nameStr;
    };

    const dealReportContent = (list, content) => {
      const reportObj = {};
      list.forEach((item) => {
        const nameStr = getModuleDisplayName(item);
        if (nameStr) {
          if (reportObj[nameStr]) {
            reportObj[nameStr].push(item);
          } else {
            const list = [];
            list.push(item);
            reportObj[nameStr] = list;
          }
        } else {
          if (reportObj.other) {
            reportObj.other.push(item);
          } else {
            const list = [];
            list.push(item);
            reportObj.other = list;
          }
        }
      });
      // console.log("reportObj ==>", reportObj);
      Object.keys(reportObj).forEach((key) => {
        if (key !== "other") {
          content += "\n" + key + "\n";
          reportObj[key].forEach((cell, index) => {
            content += index + 1;
            content += cell.splitChar;
            content += cell.reportText + "  ";
            if (Number(cell.workProgress)) {
              content += `${cell.workProgress}%  `;
            }
            content += `(${cell.reportName})`;
            content += "\n";
          });
        }
      });
      if (reportObj.other) {
        content += "\n" + "【其他】" + "\n";
        reportObj.other.forEach((cell, index) => {
          content += index + 1;
          content += cell.splitChar;
          content += cell.reportText + "  ";
          if (Number(cell.workProgress)) {
            content += `${cell.workProgress}%  `;
          }
          content += `(${cell.reportName})`;
          content += "\n";
        });
      }
      return content;
    };

    // 复制
    const copyData = (row) => {
      let content = "";
      // 上个工作日完成
      if (row.lastFinishReportList.length) {
        content +=
          `①上个工作日完成（${row.lastFinishReportList[0].reportTime}）` + "\n";
        content = dealReportContent(row.lastFinishReportList, content);
      } else {
        content += `①上个工作日完成` + "\n";
        content += "无" + "\n";
      }
      // 今日工作计划
      content +=
        "\n" +
        `②今日工作计划（${row.todayPlanReportList[0].reportTime}）` +
        "\n";
      content = dealReportContent(row.todayPlanReportList, content);
      // 上个工作日问题反馈
      content += "\n" + `③上个工作日问题反馈` + "\n";
      if (row.reportCommitRemark) {
        content += row.reportCommitRemark + "\n";
      } else {
        content += "无" + "\n";
      }
      copyInClip(content);
    };

    // 通用行合并函数（将相同多列数据合并为一行）
    const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
      const fields = ["moduleNames"];
      const cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    };

    // 初始化 -------------------------------------------
    // getPreparedData();

    // 获取所有列配置
    setTimeout(() => {
      nextTick(() => {
        tableState.columns = tableState.xTable.getColumns();
      });
    }, 100);

    onActivated(() => {
      handleSearch();
    });

    return {
      rowStyle,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      prepareData,
      deleteTableDataMethod,
      tagCheckedChange,
      getTableData,
      pagenationData,
      deleteAll,
      handleSizeChange,
      handleCurrentChange,
      toggleExpandChangeEvent,
      currentDateTime,
      copyData,
      mergeRowMethod,
      ...toRefs(tableState),
    };
  },
};
</script>

<style lang="less" scoped>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}

.expand_wrapper {
  padding: 10px;
  background: #f5f5f5;
  overflow: hidden;
}

.report_cell_title {
  font-size: 16px;
  padding: 10px 20px;
  // background-image: linear-gradient(to right top, #ec008c, #6739b6);
  background-color: #faecd8;
  color: #303133;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .time_text {
    font-size: 14px;
    font-weight: 400;
    color: #999;
  }
}

.report_cell_content {
  .report_cell_item {
    padding: 10px 20px;
    padding-right: 40px;
    display: flex;
    line-height: 20px;
    // border-bottom: 1px solid #ebeef5;
    position: relative;
    &:hover {
      background-color: #f2f2f2;
      .delete_btn {
        display: block;
      }
    }
    &:last-child {
      border: 0;
    }
  }
  .delete_btn {
    position: absolute;
    right: 0px;
    top: 50%;
    transform: translateY(-44%);
    display: none;
    cursor: pointer;
    z-index: 10;
  }
}
.input_remark_box {
  padding: 10px 20px;
  background-color: #fff;
  word-break: keep-all;
  white-space: pre-wrap; // 保留空白符序列，但是正常地进行换行
  line-height: 26px;
  color: #333;
  font-size: 16px;
}

.empty_box {
  color: #999;
  padding: 10px 20px;
  background-color: #fff;
}
</style>
